package org.ysh.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.ysh.core.shiro.ErrorCaptchaException;

import javax.servlet.http.HttpSession;

/**
 * 登录controller
 */
@Controller
public class LoginController {

    @GetMapping("/login")
    public String login(){
        return "login";
    }


    @PostMapping("/login")
    public ModelAndView login(ModelMap model, WebRequest request) {
        Object object = request.getAttribute("shiroLoginFailure",
                WebRequest.SCOPE_REQUEST);
        if (object != null) {
            if(object instanceof ErrorCaptchaException) {
                model.put("error", ((ErrorCaptchaException)object).getMessage());
            } else {
                model.put("error", "登录提交失败:账号或密码错误");
            }
            return new ModelAndView("login", model);
        } else {
            return new ModelAndView("/");
        }
    }


    // 退出
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }

}
